package com.siqi.hr.system.common.chan;

import com.siqi.hr.system.common.sql.SField;
import com.siqi.hr.system.common.sql.STable;
import com.siqi.hr.system.common.sql.TableJoinType;

import java.util.LinkedHashSet;

public class TableChan extends LinkedHashSet<STable> implements SqlChan {
	private static final long serialVersionUID = 4872813449119382190L;
	private STable mianTable;

	public StringBuilder toSqlString() {
		StringBuilder sb = new StringBuilder(this.mianTable == null ? "" : this.mianTable.toSqlString());
		for (STable table : this){
			if (table != this.mianTable){
				sb.append(join(table, table.getTableJoinType()));
			}
		}
		return sb;
	}

	protected String leftJoin() {
		return null;
	}
	
	private String join(STable table, TableJoinType tableJoinType) {
		StringBuffer joinStr = new StringBuffer();
		switch (tableJoinType) {
			case equiJoin:
			joinStr.append(" left join ").append(table.toSqlString()).append(" on ").append(new SField(table.getByName(), new STable(table.getOfByName())).toSqlString());
			joinStr.append(" = ").append(new SField(table.getName().equals("sys_custom_entity") ? "table_code" : "id", table).toSqlString());
			break;
			case right:
			joinStr.append(" right join ").append(table.toSqlString()).append(" on ").append(new SField(getMianTable().getName().equals("sys_custom_entity") ? "table_code" : "id",getMianTable()).toSqlString());
			joinStr.append(" = ").append(new SField(table.getName().equals("sys_custom_entity") ? "table_code" : "id", table).toSqlString());
			break;
			case inner:
			case left:
			joinStr.append(" left join ").append(table.toSqlString()).append(" on ").append(new SField(table.getByName(),getMianTable()).toSqlString());
			joinStr.append(" = ").append(new SField(table.getName().equals("sys_custom_entity") ? "table_code" : "id", table).toSqlString());
		}
		return joinStr.toString();
	}

	protected String join(STable table) {
		return join(table, TableJoinType.left);
	}

	public STable getMianTable() {
		return this.mianTable;
	}

	public void setMianTable(STable mianTable) {
		this.mianTable = mianTable;
	}

	public TableChan(STable mianTable) {
		this.mianTable = mianTable;
		add(mianTable);
	}

	public TableChan(String mianTableName) {
		this(new STable(mianTableName));
	}
}
